import { enumParams } from '@/enum';
import { ReduceMoney } from '@/service/db_user';
import { Main } from '@/service/types';
import { generateTree, isIOS } from '@/utils';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { UserBalanceInfoAddAmount } from '@/service/db_feature';
import { 
  DictInfoListByBelong, 
  GetBaiduyunIp2address, 
  GetImgResult, 
  GetLiveStreamingConfig, 
  QueryConfig, 
  RegionInfoGetList, 
  SecCheck 
} from '@/service/db_index';

interface CommonState {
  dictInfoTemp: string | number,
  regionInfo: Main.RegionInfo[];
  dictInfo: { 
    [key: string]: Main.DictInfo []
  };
  addressInfo: Main.BaiduyunIp2addressInfo;
}

const initState: CommonState = {
  dictInfoTemp: 0,
  dictInfo: {},
  regionInfo: [],
  addressInfo: {} as Main.BaiduyunIp2addressInfo
}

export const useCommonStore = defineStore('common', () => {
  const commonState = ref({ ...initState })
  const menuTop = ref(0);
  const menuButtonHeight = ref(38);
  const config = ref<any>({});
  const chargeConfig = ref<any>({});
  const phoneLoginConfig = ref<any>({});

  const dictInfoCallback = ref([]);
  const hasDictInfo = ref(false);

  const regionInfoCallback = ref([]);
  const hasRegionInfo = ref(false);
  
  const addressCallback = ref([]);
  const hasAddress = ref(false);

  const refresh = ref<any>({});
  
  // 获取屏幕边界到安全区域距离
  const { safeAreaInsets } = uni.getSystemInfoSync();
  const safeArea = reactive({
    top: safeAreaInsets.top || 0,
    bottom: safeAreaInsets.bottom || 0,
  })
  
  // #ifdef MP-WEIXIN
  menuTop.value = 48;
  nextTick(() => {
    const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
    menuTop.value = menuButtonInfo.top;
    menuButtonHeight.value = menuButtonInfo.height + 6;
  })
  // #endif

  /**
   * 获取字典信息
   */
  const getDictInfoList = async() => {
    try {
      let belongTo = 'dateType,profession,school,educationType,generation,matrimony,positionLevel,income,publish_people_type,';
      for (const key in enumParams.dictNameOptions) {
        belongTo += `${key},`;
      }
      const { data } = await DictInfoListByBelong({ belongTo });
      commonState.value.dictInfoTemp = +new Date();
      const list = data || [];

      const option = {}
      list.forEach(item => {
        const _item = {
          ...item,
          label: item.typeName, 
          value: item.typeCode
        }
        if (option[item.belongTo]) {
          option[item.belongTo].push(_item);
        } else {
          option[item.belongTo] = [_item];
        }
      })

      commonState.value.dictInfo = option;
      hasDictInfo.value = true;
      dictInfoCallback.value.forEach(fn => fn && fn());
      dictInfoCallback.value = [];
    } catch (error) {
      setTimeout(() => {
        getDictInfoList();
      }, 1500)
      console.log(error)
    }
  }
  
  const getRegionInfoLoading = ref(false);
  /**
   * 获取省市区信息
   */
  const getRegionInfoGetList = async() => {
    try {
      getRegionInfoLoading.value = true;
      const res = await RegionInfoGetList({});
      getRegionInfoLoading.value = false;
      console.log('获取省市区信息getRegionInfoGetList', res)
      const list = res.data || [];
      commonState.value.regionInfo = generateTree(list) || [];
      hasRegionInfo.value = true;
      regionInfoCallback.value.forEach(fn => fn && fn());
      regionInfoCallback.value = [];
    } catch (error) {
      getRegionInfoLoading.value = false;
      setTimeout(() => {
        getRegionInfoGetList();
      }, 1500)
      console.log(error)
    }
  }

  /** 通过ip获取地址 */
  const getBaiduyunIp2address = async() => {
    try {
      const res = await GetBaiduyunIp2address({});
      commonState.value.addressInfo = res.data || {} as Main.BaiduyunIp2addressInfo;
      hasAddress.value = true;
      addressCallback.value.forEach(fn => fn && fn());
      addressCallback.value = [];
    } catch (error) {
      console.log(error)
    }
  }

  /**
   * 充值提示
   * @param data 充值数据
   * @param callback 回调函数
   * @param isRecharge 是否充值 充值true 消费现金false
   * @param message 确认充值提示框
   */
  const paymentMsgConfirm = (
    data, 
    callback = () => {}, 
    isRecharge = false, 
    message,
    isSelectWeChat = false,
    reduceMoneyApi = null,
  ) => {
    if (isSelectWeChat) {
      !isRecharge && reduceMoney(data, callback, reduceMoneyApi);
      isRecharge && confirmPayment(data, callback);
      return;
    }
    message
      .confirm({
        msg: `是否直接充值`,
        title: '乐缘币不足'
      })
      .then(() => {
        !isRecharge && reduceMoney(data, callback, reduceMoneyApi);
        isRecharge && confirmPayment(data, callback);
      })
      .catch(() => {
        console.log('点击了取消按钮')
      })
  }

  // 充值
  const confirmPayment = async (data, callback) => {
    try {
      uni.showLoading({
        title: '正在调起支付'
      });
      const res = await UserBalanceInfoAddAmount(data);
      if (res.code != 200) {
        uni.hideLoading();
        return
      }
      payment(res.data, callback);
    } catch (error) {
      uni.hideLoading();
      console.log(error)
    }
  }
  
  /** 消费现金 */
  const reduceMoney = async (data, callback, reduceMoneyApi = null) => {
    try {
      uni.showLoading({
        title: '正在调起支付'
      });
      const api = reduceMoneyApi ? reduceMoneyApi : ReduceMoney;
      const res = await api(data);
      if (res.code != 200) {
        uni.hideLoading();
        return;
      }
      payment(res.data, callback);
    } catch (error) {
      uni.hideLoading();
      console.log(error)
    }
  }

  // 调起微信支付
  const payment = ({
    nonceStr, packageValue, paySign, signType, timeStamp
  }, callback) => {
    if (isIOS() && chargeConfig.value.typeName === 'false') {
      uni.showToast({
        title: '由于相关规范，iOS功能暂不可用',
        icon: 'none'
      })
      return 
    }
    wx.requestPayment({
      timeStamp,
      nonceStr,
      package: packageValue,
      signType,
      paySign,
      success: (res) => {
        uni.hideLoading();
        callback && callback();
      },
      fail: (err) => {
        uni.hideLoading();
        console.log('fail:' + JSON.stringify(err));
      }
    })
  }
  
  const liveStreamingConfig = ref({} as Main.LiveStreamingConfig);
  /** 获取用户直播配置表详情 */
  const getLiveStreamingConfig = async() => {
    try {
      const res = await GetLiveStreamingConfig({
        id: 1,
      });
      liveStreamingConfig.value = res.data || {} as Main.LiveStreamingConfig;
    } catch (error) {
      console.log(error)
    }
  }
  
  /** 配置vip显隐 */
  const queryConfig = async() => {
    try {
      const res = await QueryConfig({
        typeCode: 'showMember',
        belongTo: 'showInfo',
      });
      config.value = res.data || {};
    } catch (error) {
      console.log(error)
    }
  }
  
  /** 配置充值显隐 */
  const queryChargeConfig = async() => {
    try {
      const res = await QueryConfig({
        typeCode: 'showCharge',
        belongTo: 'showInfo',
      });
      chargeConfig.value = res.data || {};
    } catch (error) {
      console.log(error)
    }
  }
  
  /** 手机号显示隐藏 */
  const queryPhoneLoginConfig = async() => {
    try {
      const res = await QueryConfig({
        typeCode: 'showPhoneLogin',
        belongTo: 'showInfo',
      });
      phoneLoginConfig.value = res.data || {};
    } catch (error) {
      console.log(error)
    }
  }

  function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  // 获取图片校验回调信息
  const getImgResult = async (callback, data) => {
    try {
      const _checkInfoList = data.checkInfoList || [];
      const list = _checkInfoList.filter(item => item.checkType === 'img').map(item => item.message);
      const traceIds = list.join(',');

      const res = await GetImgResult({ traceIds });
      if (res.code == '800088') {
        await sleep(1500);
        getImgResult(callback, data);
        return;
      }

      uni.hideLoading();
      const _data = res.data || {};
      const _list = [];
      for (const key in _data) {
        const item = _data[key] || '';
        const itemRes = item ? JSON.parse(item) : {};
        const _suggest = itemRes.suggest || '';
        _list.push(_suggest);
      }

      const flag = _list.some(item => item !== 'pass');
      if (flag) {
        return uni.showToast({ 
          title: '内容含有敏感信息，请修改后重试！', 
          icon: 'none' 
        });
      }
      
      callback && callback(res.data);
    } catch (error) {
      uni.hideLoading();
      console.log(error)
    }
  }

  /** 敏感信息校验 */
  const secCheck = async(data: Main.SecCheckParams, callback) => {
    try {
      // 微信小程序需要校验
      // #ifdef MP-WEIXIN
      uni.showLoading({
        title: '正在校验文本',
        mask: true
      })
      const list = data.checkInfoList.filter(item => !!item.content);
      const res = await SecCheck({
        userId: data.userId,
        checkInfoList: list
      });
      uni.hideLoading();
      
      if (!res.data.result) {
        return uni.showToast({ 
          title: '内容含有敏感信息，请修改后重试！', 
          icon: 'none' 
        });
      }
      
      uni.showLoading({
        title: '正在校验图片',
        mask: true
      })
      // await sleep(5000);
      // uni.hideLoading();
      getImgResult(callback, res.data);
      // #endif

      // 其它不需要
      // #ifndef MP-WEIXIN
      callback && callback({ data: { result: true } });
      // #endif
    } catch (error) {
      console.log(error)
    }
  }
  
  return {
    menuTop,
    menuButtonHeight,
    commonState,
    safeArea,
    config,
    chargeConfig,
    phoneLoginConfig,
    liveStreamingConfig,
    dictInfoCallback,
    hasDictInfo,
    regionInfoCallback,
    hasRegionInfo,
    addressCallback,
    hasAddress,
    getRegionInfoLoading,
    refresh,
    secCheck,
    queryChargeConfig,
    reduceMoney,
    paymentMsgConfirm,
    payment,
    confirmPayment,
    getDictInfoList,
    getRegionInfoGetList,
    getBaiduyunIp2address,
    queryConfig,
    getLiveStreamingConfig,
    queryPhoneLoginConfig
  }
}, { persist: true })
